package com.iflytek.jzcpx.procuracy.web;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Optional;
import java.util.regex.Pattern;

import cn.hutool.core.util.NumberUtil;
import com.iflytek.jzcpx.procuracy.common.util.Logs;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.StopWatch;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 11:15
 */
@SpringBootApplication(scanBasePackages = {"com.iflytek.jzcpx", "com.iflytek.icourt"})
@MapperScan("com.iflytek.jzcpx.procuracy.*.dao")
@EnableScheduling
public class ViewProcuracyWebApplication {
    protected static final Logger logger = LoggerFactory.getLogger(ViewProcuracyWebApplication.class);

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = new SpringApplicationBuilder(
                ViewProcuracyWebApplication.class).logStartupInfo(false)
                                                  // .banner(new AppBanner())
                                                  .run(args);
        stopWatch.stop();
        ServerProperties serverProperties = context.getBean(ServerProperties.class);
        Integer port = serverProperties.getPort();
        String contextPath = serverProperties.getServlet().getContextPath();
        String ip = Optional.ofNullable(getLocalAddress0()).map(InetAddress::getHostAddress).orElse("127.0.0.1");
        logger.info("{} 服务启动完成，耗时:{}s，swagger页面: http://{}:{}{}/swagger-ui.html", context.getId(),
                    stopWatch.getTotalTimeSeconds(), ip, port, contextPath);

        String property = context.getEnvironment().getProperty("loggger.content.max-length");
        if (NumberUtil.isNumber(property)) {
            Logs.maxLength = Integer.parseInt(property);
        }
    }

    private static InetAddress getLocalAddress0() {
        InetAddress localAddress = null;
        try {
            localAddress = InetAddress.getLocalHost();
            if (isValidAddress(localAddress)) {
                return localAddress;
            }
        }
        catch (Throwable e) {
            //
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidAddress(address)) {
                                        return address;
                                    }
                                }
                                catch (Throwable e) {
                                    //
                                }
                            }
                        }
                    }
                    catch (Throwable e) {
                        //
                    }
                }
            }
        }
        catch (Throwable e) {
            //
        }
        return localAddress;
    }

    private static boolean isValidAddress(InetAddress address) {
        Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
        if (address == null || address.isLoopbackAddress())
            return false;
        String name = address.getHostAddress();
        return (name != null && !"0.0.0.0".equals(name) && !"127.0.0.1".equals(name) && IP_PATTERN.matcher(name)
                                                                                                  .matches());
    }

}
